﻿namespace Cavy.UdpClient
{
    public class UdpRoom : MessageFactory
    {
        private Transport _transport;

        public Transport Transport
        {
            set
            {
                _transport = value;
                _transport.GameId = GameId;
            }
            get => _transport;
        }
        internal System.Collections.Generic.List<IpEndPoint> _connections = new System.Collections.Generic.List<IpEndPoint>();
        internal System.Collections.Generic.List<(Message_FindRoomLanResponse room, IpEndPoint)> _findRooms = new System.Collections.Generic.List<(Message_FindRoomLanResponse room, IpEndPoint ipEndPoint)>();
        public System.Collections.Generic.List<(Message_FindRoomLanResponse room, IpEndPoint ipEndPoint)> FindRooms => _findRooms;
        public uint GameId;
        public string RoomName;
        public UdpRoom(uint gameId)
        {
            GameId = gameId;
        }

        /// <summary>
        /// 销毁房间
        /// </summary>
        public void DestroyRoom()
        {
            Transport?.Close();
            Transport?.Dispose();
            Transport = null;
        }

        /// <summary>
        /// 开启房间监听
        /// </summary>
        public void StartListener()
        {
            Transport.OnReceived += AnalysisFrame;
            Transport.ReceiveAsync();
        }

        public void CreateRoom(string roomName)
        {
            RoomName = roomName;
        }

        /// <summary>
        /// 搜寻房间
        /// </summary>
        public void FindRoomLan()
        {
            Transport.BroadcastLan(new Message_FindRoomLan());
        }

        /// <summary>
        /// 解析帧数据
        /// </summary>
        /// <param name="result"></param>
        protected virtual void AnalysisFrame(UdpResult result)
        {
            (bool success, IMessage message) = _Analysis(GameId, result.Buffer, result.RemoteEndPoint);
            if (success && message == null)
            {
                int count = _connections.Count;
                int dataLength = result.Buffer.Length;
                for (int i = 0; i < count; i++)
                {
                    Transport.Send(result.Buffer, dataLength, _connections[i].Address, _connections[i].Port);
                }
            }
        }

        /// <summary>
        /// 停止搜寻房间
        /// </summary>
        public void StopRoomListener()
        {
            
        }
    }
}